
#include "PAL.h"
#include "MutexLock.h"


#define HIGHEST_PRI			0
#define LOWEST_PRI			127

extern "C"{
extern void InterruptPrioritySet(unsigned int,unsigned int);
extern void InterruptOff(unsigned int);
extern void InterruptOn(unsigned int);
extern void InterruptAllOff(unsigned int);
extern void InterruptAllOn(unsigned int);
}
namespace PAL
{



static volatile u32	ISROwner[ISR_NUM];
static volatile _mlock	ISRLocker = {NULL,NULL};

volatile void (*ISR[ISR_NUM])(void);

volatile unsigned int INTOwner[ISR_NUM];




int AddInterrupt(unsigned int ISRNum,unsigned int Priority, void (*fnhandle)(void),unsigned int mark)
{
if(Priority > LOWEST_PRI)
	return 0;
MUTEX_Lock(&ISRLocker,run);
	if(ISR[ISRNum] != NULL)
	{
	MUTEX_UnLock(&ISRLocker,run);
		return 0;
	}
	ISR[ISRNum] = fnhandle;
	ISROwner[ISRNum] = mark;
	InterruptPrioritySet(ISRNum,Priority);
	InterruptOn(ISRNum);
MUTEX_UnLock(&ISRLocker,run);
//	InterruptRegist(ISRNum,Priority,fnhandle);
	
	return 1;
}

unsigned int GetInterrupt(unsigned int Priority,void (*fnhandle)(void),unsigned int mark)
{
if(Priority > LOWEST_PRI)
	return 0;
	unsigned int i = 0;
MUTEX_Lock(&ISRLocker,run);
	while(i < ISR_NUM && ISR[i] != NULL)
	{
		i++;
	}

	if(i >= ISR_NUM)
	{
MUTEX_UnLock(&ISRLocker,run);
		return (~0);
	}
	ISROwner[i] = mark;
	ISR[i] = fnhandle;
	InterruptOn(i);
MUTEX_UnLock(&ISRLocker,run);
//	InterruptRegist(i,fnhandle);
	
	
	
}

int DeleteInterrupt(unsigned int ISRNum)
{
MUTEX_Lock(&ISRLocker,run);
	ISROwner[ISRNum] = 0;
	ISR[ISRNum] = NULL;
	InterruptOff(ISRNum);
MUTEX_UnLock(&ISRLocker,run);
//	InterruptUnRegist(ISRNum);
//TODO
}

int PauseInterrupt(unsigned int ISRNum)
{
MUTEX_Lock(&ISRLocker,run);
	if(ISR[ISRNum] != NULL)
	{
	//TODO
	InterruptOff(ISRNum);
MUTEX_UnLock(&ISRLocker,run);
		return 1;
	}
MUTEX_UnLock(&ISRLocker,run);
}

int ContinueInterrupt(unsigned int ISRNum)
{
MUTEX_Lock(&ISRLocker,run);
	if(ISR[ISRNum] != NULL)
	{
	//TODO
	InterruptOn(ISRNum);
MUTEX_UnLock(&ISRLocker,run);
		return 1;
	}	
MUTEX_UnLock(&ISRLocker,run);
}


}
